import random
import re

from django.core.paginator import Paginator
from django.http import HttpResponse
from rest_framework.response import Response
from rest_framework.views import APIView

from .comm import send_message, get_redis
from .models import News, User
from .ser import NewsSer


class NewAPIView(APIView):
    def post(self, request):
        data = NewsSer(data=request.data)
        if data.is_valid():
            data.save()
            return Response({'code': 200, 'meg': '添加成功'})
        else:
            print(data.errors)
            return Response({'code': 10010})

    def get(self, request):
        news = News.objects.all()
        p = Paginator(news, 2)
        cpage = request.GET.get('page')
        newsR = p.page(cpage)
        ser = NewsSer(newsR, many=True)
        return Response({'code': 200, 'list': ser.data, 'tpage': p.num_pages})


# 注册接口
class Register(APIView):
    def post(self, request):
        username = request.data.get('username')
        # 格式是否正确
        name = re.match('/\w{5,20}$/', username)
        if not name:
            return Response({'code': 1001})
        # 是否唯一
        else:
            user = User.objects.filter(username=username)
            if user:
                return Response({"meg": "用户名已存在", 'code': 1002})
            else:
                # 验证密码是否为空
                password1 = request.data.get('password1')
                if not password1:
                    return Response({'meg': '密码不能为空'})
                else:
                    # 密码格式是否正确
                    pd = re.match('/\w{8,20}$/', password1)
                    if not pd:
                        return Response({'meg': '密码格式不对', 'code': 2001})
                    else:
                        password2 = request.data.get('password2')
                        if password1 != password2:
                            return Response({'meg': '密码输入不一致', 'code': 2002})
                        else:
                            # 手机号
                            mobile = request.data.get('mobile')
                            # 格式是否正确
                            phone = re.match('^1[3-9]\d{9}$', mobile)
                            if not phone:
                                return Response({"meg": "手机号输入不正确", 'code': 3001})
                            # 验证码验证newcode，redis取根据手机号
                            smscode = request.data.get('smscode')
                            conn = get_redis()
                            code = str(conn.get(mobile), encoding='utf8')
                            if smscode == code:
                                agree = request.data.get("agree")
                                if agree == False:
                                    return Response({'code': 5001, 'meg': '请勾选用户协议'})
                                else:
                                    from django.contrib.auth.hashers import make_password
                                    user = User.objects.create(
                                        uasename=username,
                                        password=make_password(password1)
                                    )
                                    return Response(
                                        {'code': 200, 'meg': '注册成功', "userid": user.id, "username": username})
                            else:
                                return Response({"meg": "短信验证失败", "code": 4001})


class Text(APIView):
    def get(self, request):
        # send_message(18638748017, 123456, 1)
        get_redis()
        return Response("ok")


class SendSms(APIView):
    def post(self, request):
        mobile = request.data.get('mobile')
        # 验证图片验证码，通过后才发短信
        uid = request.data.get("uid")
        # 用户输入的
        imagecode = request.data.get("imagecode")
        conn = get_redis()
        imgcode = conn.get(uid)
        if imagecode:
            imgcode = str(imgcode, encoding="utf8")
            if imagecode == imgcode:
                codesms = random.randint(100000, 999999)
                res = send_message(mobile, str(codesms), 1)
                code = 10010
                if res:
                    code = 200
                    # 发送验证码成功后存入redis
                    conn = get_redis()
                    conn.setex(mobile, 60, codesms)
                return Response({"code": code})
        return Response({"code": 20010})


#  注册时图形验证
class CreateCaptcha(APIView):
    def get(self, request):
        uuid = request.GET.get('uuid')
        from utils.captcha.captcha import captcha
        name, text, img = captcha.generate_captcha()
        # redis存储
        conn = get_redis()
        conn.setex(uuid, 60, text)
        return HttpResponse(img, content_type="image/jpg")
